import { Button, Flex, Card, Space, Avatar,List, Tooltip, Spin,Tabs, Empty, Divider, Tour, Skeleton, Radio, message } from 'antd';
import { SearchOutlined,UserOutlined,AntDesignOutlined,EllipsisOutlined } from '@ant-design/icons';
import { useEffect, useRef, useState } from 'react';
import InfiniteScroll from 'react-infinite-scroll-component';
import VirtualList from 'rc-virtual-list';

/**
 * 1.Tabs 标签页
 * 2.Tabs 可编辑标签页
 * 3.List 列表
 * 4.List 加载更多
 * 5.List 翻页控件
 * 6.List 滚动自动加载列表 底部实现 骨架屏or加载动画
 * 7.List 无限加载list 结合 rc-virtual-list 实现滚动加载无限长列表，能够提高数据量大时候长列表的性能
 */

/**
 * Tabs 标签页
 */
const TabsWidget=()=>{
    return(
        <Card title="Tabs 标签页">
            <Tabs
                defaultActiveKey='2' // 默认选择哪个标签
                centered
                indicator={{ // 指示条宽度和对齐方式。
                    size:(origin)=>origin-40,
                    align:"start"
                }}
                tabBarExtraContent={<Button>Extra Action</Button>} // 右边添加view
                items={new Array(3).fill(null).map((_,index)=>{
                    const id = String(index+1)
                    return{
                        label:`Tab ${id}`,
                        key:id,
                        children:`Tab 内容 ${id}`,
                        // disabled:true 禁用
                        icon:<UserOutlined/>, // 标签添加图片
                    }
                })}
            />
            <br/>
            <br/>
            <Tabs
                defaultActiveKey='2' // 默认选择哪个标签
                type={"card"} // 设置类型
                items={new Array(3).fill(null).map((_,index)=>{
                    const id = String(index+1)
                    return{
                        label:`Tab ${id}`,
                        key:id,
                        children:`Tab 内容 ${id}`,
                        // disabled:true 禁用
                        icon:<UserOutlined/>, // 标签添加图片
                    }
                })}
            />
        </Card>
    )
}
/**
 * Tabs 可编辑标签页
 */
const TabsEditWidget=()=>{
    
    const defaultPanes = new Array(3).fill(null).map((_,index)=>{
        const id = String(index + 1)
        return{
            label:`Tab ${id}`,
            children:`Tab的内容 ${index+1}`,
            key:id
        }
    })

    const [activeKey,setActiveKey] = useState(defaultPanes[0].key)
    const [items,setItems] = useState(defaultPanes)
    const newTabIndex = useRef(0)
    const onChange =(key)=>{
        setActiveKey(key)
    }

    const add =()=>{
        const newActiveKey = `newTab${newTabIndex.current++}`
        console.log("ah index ==",newTabIndex)
        setItems([
            ...items,
            {
                label:"新标签",
                children:"新标签Pane",
                key:newActiveKey
            }
        ])
        setActiveKey(newActiveKey)
    }

    const remove = (targetKey) =>{
        const targetIndex = items.findIndex((pane)=>pane.key === targetKey)
        const newPanes = items.filter((pane)=>pane.key !== targetKey)
        if(newPanes.length && targetKey === activeKey){
            const {key} = newPanes[targetIndex === newPanes.length?targetIndex-1:targetIndex]
            setActiveKey(key)
        }
        setItems(newPanes)
    }

    const onEdit=(targetKey,action) => {
        if(action === "add"){
            add()
        }else{
            remove(targetKey)
        }
    }

    return(
        <Card title="Tabs 可编辑标签页">
            <Tabs
            onChange={onChange}
            activeKey={activeKey}
            type={"editable-card"}
            onEdit={onEdit}
            items={items}
            />
        </Card>
    )

}

/**
 * List 列表
 */
const ListWidget =()=>{
    const data = [
        {
          title: 'Ant Design Title 1',
        },
        {
          title: 'Ant Design Title 2',
        },
        {
          title: 'Ant Design Title 3',
        },
        {
          title: 'Ant Design Title 4',
        },
      ];
    return(
        <Card title="List 列表" style={{width:"100%"}}>
            <List
            header={<div>Header</div>}
            footer={<div>Footer</div>}
            itemLayout={"horizontal"}
            bordered
            dataSource={data}
            renderItem={(item,index)=>(
                <List.Item>
                    <List.Item.Meta
                    avatar={<Avatar src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${index}`}/>}
                    title={<a href='https://www.baidu.com' target={"_blank"} rel={"noreferrer"}>{item.title}</a>}
                    description="Ant Design, a design language for background applications, is refined by Ant UED Team"
                    />
                </List.Item>
            )}
            >

            </List>
        </Card>
    )
}

/**
 * List 加载更多
 */
const ListLoadMore=()=>{
    const count = 3;
    const fakeDataUrl = `https://randomuser.me/api/?results=${count}&inc=name,gender,email,nat,picture&noinfo`;

    const [initLoading, setInitLoading] = useState(true); // 用于第一次加载，加载动画
    const [loading, setLoading] = useState(false); // 用于判断是否显示加载更多时加载动画
    const [data, setData] = useState([]); // 用于缓存加载数据，显示加载骨架屏的假数据。
    const [list, setList] = useState([]); // 缓存真实数据

    // 打开页面先请求三个数据
    useEffect(()=>{
        fetch(fakeDataUrl)
        .then((res)=>res.json())
        .then((res)=>{
            setInitLoading(false)
            setData(res.results)
            setList(res.results)
        })
    },[])

    // 加载更多。先加载几个假数据，用于显示骨架图，接口返回数据后，再替换新数据。
    const onLoadMore=()=>{
        setLoading(true)
        setList(
            data.concat(
                [...new Array(count)].map(()=>({
                    loading:true,
                    name:{},
                    picture:{}
                }))
            )
        )
        fetch(fakeDataUrl)
        .then((res)=>res.json())
        .then((res)=>{
            const newData = data.concat(res.results);
            console.log(res.results)
            setData(newData)
            setList(newData)
            setLoading(false)
            // window.dispatchEvent(new Event("resize"))
        })
    }

    const loadMore = !initLoading && !loading ? (
        <div
        style={{
            textAlign:"center",
            marginTop:12,
            height:32,
            lineHeight:"32px"
        }}
        >
            <Button onClick={onLoadMore}>加载更多</Button>
        </div>
    ):null

    return(
        <Card title="ListLoadMore 加载更多">
            <List
            className='demo-loadmore-list'
            loading={initLoading} // 当页面刷新显示加载动画
            itemLayout={"horizontal"}
            loadMore={loadMore} // 显示加载更多view
            footer={<div style={{display:"flex",alignItems:"center",justifyContent:"center",width:"100%",height:60,backgroundColor:"rosybrown"}}>Footer</div>}
            dataSource={list}
            renderItem={(item)=>(
                <List.Item
                actions={[<a>编辑</a>,<a>更多</a>]}
                >
                    <Skeleton
                    avatar
                    loading={item.loading} // 用于是否显示骨架屏
                    paragraph={{ // 段落有几行
                        rows:1
                    }}
                    active // 动画
                    >
                        <List.Item.Meta
                        avatar={<Avatar src={item.picture.large}/>}
                        title={<a href='https://www.baidu.com'>{item.name?.last}</a>}
                        description="Ant Design, a design language for background applications, is refined by Ant UED Team"
                        />
                        <div>content</div>
                    </Skeleton>
                </List.Item>
            )
            }
            />
        </Card>

    )
}

/**
 * List 翻页控件
 */
const ListPaginationWidget=()=>{
    const data = [
        {
            title: 'Ant Design Title 1',
        },
        {
            title: 'Ant Design Title 2',
        },
        {
            title: 'Ant Design Title 3',
        },
        {
            title: 'Ant Design Title 4',
        },
    ];
    const positionOptions = ['top', 'bottom', 'both'];
    const alignOptions = ['start', 'center', 'end'];

    const [position, setPosition] = useState('bottom');
    const [align, setAlign] = useState('center');

   return(
    <Card title="List 翻页位置">
        <Space
        direction='vertical'
        style={{
            marginBottom:"20px"
        }}
        size={"middle"}
        >
            <Space>
                <spen>Pagination Position:</spen>
                <Radio.Group
                optionType={"button"}
                value={position}
                onChange={(e)=>{
                    setPosition(e.target.value)
                }}
                >
                    {
                        positionOptions.map((item)=>(
                            <Radio.Button key={item} value={item}>
                                {item}
                            </Radio.Button>
                        ))
                    }
                </Radio.Group>
            </Space>

            <Space>
                <span>Pagination Align:</span>
                <Radio.Group
                optionType='button'
                value={align}
                onChange={(e)=>{
                    setAlign(e.target.value)
                }}
                >
                    {
                        alignOptions.map((item)=>(
                            <Radio.Button key={item} value={item}>
                                {item}
                            </Radio.Button>
                        ))
                    }

                </Radio.Group>
            </Space>
        </Space>
        <List
        pagination={{
            position,
            align
        }}
        dataSource={data}
        renderItem={(item,index)=>(
            <List.Item>
                <List.Item.Meta
                avatar={<Avatar src={`https://api.dicebear.com/7.x/miniavs/svg?seed=${index}`}/>}
                title={<a href="https://ant.design">{item.title}</a>}
                description="Ant Design, a design language for background applications, is refined by Ant UED Team"
                />
            </List.Item>
        )}
        >

        </List>
    </Card>
   ) 

}

/**
 * 滚动自动加载列表 底部实现 骨架屏or加载动画
 */
const ListAutoJiaZaiData=()=>{
    const [loading,setLoading] = useState(false)
    const [data,setData] = useState([])
    const loadMoreData =()=>{
        if(loading){
            return;
        }
        setLoading(true)
        fetch('https://randomuser.me/api/?results=10&inc=name,gender,email,nat,picture&noinfo')
            .then((res)=>res.json())
            .then((body)=>{
                setData([...data,...body.results]);
                setLoading(false)
            })
            .catch(()=>{
                setLoading(false)
            })
    }

    useEffect(()=>{
        loadMoreData()
    },[])

    return(
        <Card title="滚动列表自动加载数据">
            <div
            id='scrollableDiv'
            style={{
                height:400,
                overflow:"auto",
                padding:"0 16px",
                border:"1px solid rgba(140,140,140,0.35)",
            }}
            >
                <InfiniteScroll
                dataLength={data.length}
                next={loadMoreData} // 加载更多的方法
                hasMore={data.length<50} // 触发加载更多的条件
                loader={ // 加载动画样式
                    // 骨架屏
                    // <Skeleton 
                    // avatar
                    // paragraph={{
                    //     rows:1
                    // }}
                    // active
                    // />

                    // 加载框
                    <div style={{
                        width:"100%",
                        height:60,
                        display:"flex",
                        alignItems:"center",
                        justifyContent:"center"
                    }}>
                        <Spin/>
                    </div>
                    
                }
                endMessage={<Divider plain>It is all, nothing more 🤐</Divider>}
                scrollableTarget="scrollableDiv"
                >
                    <List
                    dataSource={data}
                    renderItem={(item)=>(
                        <List.Item key={item.email}>
                            <List.Item.Meta
                            avatar={<Avatar src={item.picture.large}/>}
                            title={<a href='https://www.baidu.com'>{item.name.last}</a>}
                            description={item.email}
                            />
                            <div>Content</div>
                        </List.Item>
                    )}
                    />
                </InfiniteScroll>
            </div>
        </Card>
    )
}

/**
 * 无限加载list 结合 rc-virtual-list 实现滚动加载无限长列表，能够提高数据量大时候长列表的性能。
 */
const ListInfiniteData=()=>{
    const fakeDataUrl = 'https://randomuser.me/api/?results=20&inc=name,gender,email,nat,picture&noinfo';
    const containerHeight = 400;

    const [data,setData] = useState([])
    const appendData=()=>{
        fetch(fakeDataUrl)
            .then((res)=>res.json())
            .then((body)=>{
                setData(data.concat(body.results))
                message.success(`${body.results.length} more items loaded!`)
            })
    }

    useEffect(()=>{
        appendData()
    },[])

    const onScroll =(e)=>{
        if(Math.abs(e.currentTarget.scrollHeight - e.currentTarget.scrollTop - containerHeight) <= 1){
            appendData()
        }
    }

    return(
        <Card title="无限加载list 结合 rc-virtual-list">
             <List>
                <VirtualList
                data={data}
                height={containerHeight}
                itemHeight={47}
                itemKey={"email"}
                onScroll={onScroll}
                >
                    {
                        (item)=>(
                            <List.Item key={item.email}>
                                <List.Item.Meta
                                avatar={<Avatar src={item.picture.large}/>}
                                title={<a href='http://www.baidu.com' target={"_blank"} rel="noreferrer">{item.name.last}</a>}
                                description={item.email}
                                />
                                <div>Content</div>
                            </List.Item>
                        )
                    }

                </VirtualList>
            </List>
        </Card>
       
    )
}


const DateShowWidgetTwo =()=>{
    return(
      <Space direction='vertical' style={{width:"100%"}}>
        <TabsWidget/>
        <TabsEditWidget/>
        <ListWidget/>
        <ListLoadMore/>
        <ListPaginationWidget/>
        <ListAutoJiaZaiData/>
        <ListInfiniteData/>
      </Space>
    )
}

export default DateShowWidgetTwo